package com.accessibleworlds.gateway;

import java.io.File;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;

import com.accessibleworlds.R;
import com.accessibleworlds.blind.BlindUserGatewayPage;
import com.accessibleworlds.blind.BlindUserMainPage;
import com.accessibleworlds.blind.MultitouchGestureListener;
import com.accessibleworlds.user.StartPage;
import com.accessibleworlds.user.UserPage;
import com.accessibleworlds.util.Connections;
import com.accessibleworlds.util.SharedVariables;
import com.accessibleworlds.util.TextToSpeeches;
import com.accessibleworlds.util.TextToSpeechesGoogle;
import com.accessibleworlds.util.TextToSpeechesPico;

public class Main extends Activity implements MultitouchGestureListener{
	
	private long startTime, finishTime;
	
	private Intent intent = new Intent();
	
	private Thread thread;
	
	private boolean isInvisible,isFinished;
	
	private TextToSpeeches tts = null;
	
	private SharedPreferences preferences;

    private final int ID_MENU_Logout = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setTheme(R.style.normalscreen);
		
		preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		
		SharedVariables.currentLanguage = Integer.parseInt(preferences.getString("language","0"));
		
		if(preferences.getBoolean("autoLogin", false)) {
			setContentView(R.layout.mainwithoutgesture);
		}
		else {
			setContentView(R.layout.main);
		}
		
		Connections.initializeVariables();
		
		File folder = new File(SharedVariables.folderName);
		if(!folder.exists()) {
			folder.mkdirs();
		}
		
		isInvisible = false;
		isFinished = false;
        startTime = System.currentTimeMillis();
        
        Locale.setDefault(SharedVariables.languagesLocates[SharedVariables.currentLanguage]);
		
        /**
         * if autoLogin is enable, try to login user.
         * Else use Text To Speech.
         */
		thread = new Thread(new Runnable() {
			public void run() {
				if(preferences.getBoolean("autoLogin", false)) {
					connection();
				}
				else {
					tts();
				}
			}
		});
		thread.start();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		isInvisible = false;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		isInvisible = true;
		if(tts!= null) {
			tts.close();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		isFinished = true;
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		isInvisible = true;
	}
	
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
	
	private void tts() {
		if("0".equalsIgnoreCase(getResources().getStringArray(R.array.languageValues)[SharedVariables.currentLanguage]))
			tts = new TextToSpeechesPico();
		else
			tts = new TextToSpeechesGoogle();
		tts.speak(this, getResources().getStringArray(R.array.welcomeAccessibleWorlds)[SharedVariables.currentLanguage]);
	}

	/**
	 * This is for login operation.
	 * Using saved email and password, application tries to login.
	 * if everything goes fine, show user page.
	 * else show login page.
	 */
	private void connection() {
		String emailString = preferences.getString("email", "");
		String passwordString = preferences.getString("password", "");
		
		if(emailString.length()!=0 && emailString.length()<=100 && passwordString.length()!=0 && passwordString.length()<=255) {
			if(Connections.serviceStatus()) {
				try {
					String url = Connections.URI+Connections.login;
					String [] parameters = {"accessCode","email","password"};
					String [] paramaterValues = {SharedVariables.accessCode,emailString,passwordString};
					
					String [] takenData = Connections.connection(url,parameters,paramaterValues);
					
					if("OK".equalsIgnoreCase(takenData[0])) {
						goToIntent(takenData);
						finish();
					}
					else
						goToLogin();
				} catch (Exception e) {
					goToLogin();
				}
			}
			else {
				finishTime = System.currentTimeMillis();
				if((2000-(finishTime-startTime))>0) {
					try {
						Thread.sleep(2000-(finishTime-startTime));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				//if application does not reach web service, show an alert dialog.
				runOnUiThread(new Runnable() {
					public void run() {						
						AlertDialog alertDialog = new AlertDialog.Builder(Main.this).create();
						alertDialog.setTitle(getResources().getStringArray(R.array.connectionProblem)[SharedVariables.currentLanguage]);
						alertDialog.setMessage(getResources().getStringArray(R.array.connectionProblemException)[SharedVariables.currentLanguage]);
						alertDialog.setButton(getResources().getStringArray(R.array.tryAgain)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								new Thread(new Runnable() {
									public void run() {
										startTime = System.currentTimeMillis();
										thread.run();
									}
								}).start();
							}
						});
						alertDialog.setButton2(getResources().getStringArray(R.array.exit)[SharedVariables.currentLanguage], new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
						alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
						    public void onCancel(DialogInterface dialog) {
						    	goToStartPage();
						    }
						});
						if(!isFinished) {
							alertDialog.show();
						}						
					}
				});
			}
		}
		else {
			goToLogin();
		}
	}
	
	/**
	 * This is for showing user page and saving user data in preferences.
	 * @param takenData User information such as userID,birthday, etc.
	 */
	private void goToIntent(String [] takenData) {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		if(preferences.getBoolean("blindUserMode", false))
			intent = new Intent(this,BlindUserMainPage.class);
		else
			intent = new Intent(this,UserPage.class);
		Bundle bundle = new Bundle();
		bundle.putString("previousID", SharedVariables.mainID);
		bundle.putBoolean("isInvisible", isInvisible);
		intent.putExtras(bundle);
		
		SharedPreferences savePreferences = getSharedPreferences(SharedVariables.fileName, MODE_PRIVATE);
		SharedPreferences.Editor saveEditor = savePreferences.edit();
		saveEditor.putString("userID", takenData[1]);
		saveEditor.putString("email", takenData[2]);
		saveEditor.putString("password", takenData[3]);
		saveEditor.putString("lastName", takenData[4]);
		saveEditor.putString("firstName", takenData[5]);
		saveEditor.putString("birthday", takenData[6]);
		saveEditor.commit();
		
		finishTime = System.currentTimeMillis();
		if((2000-(finishTime-startTime))>0)
			try {
				Thread.sleep(2000-(finishTime-startTime));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		runOnUiThread(new Runnable() {
			public void run() {
				if(!isFinished) {
					startActivity(intent);
    				overridePendingTransition(R.anim.fade, R.anim.hold);
    			}
			}
		});
	}
	
	/**
	 * This is for showing startPage.
	 * This is called, when autoLogin is false and user does not want to go blindUserMode.
	 */
	private void goToStartPage () {
		intent = new Intent(this,StartPage.class);
		Bundle bundle = new Bundle();
		bundle.putString("previousID", SharedVariables.mainID);
		bundle.putBoolean("isInvisible", isInvisible);
		intent.putExtras(bundle);
		
		finishTime = System.currentTimeMillis();
		if((2000-(finishTime-startTime))>0)
			try {
				Thread.sleep(2000-(finishTime-startTime));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		
		runOnUiThread(new Runnable() {
			public void run() {
				if(!isFinished) {
    				startActivity(intent);
    				overridePendingTransition(R.anim.fade, R.anim.hold);
    				finish();
    			}
			}
		});
	}
	
	/**
	 * This is for going LoginPage.
	 */
	private void goToLogin () {
		intent = new Intent(this,Login.class);
		Bundle bundle = new Bundle();
		bundle.putString("previousID", SharedVariables.mainID);
		bundle.putBoolean("isInvisible", isInvisible);
		intent.putExtras(bundle);
		
		finishTime = System.currentTimeMillis();
		if((2000-(finishTime-startTime))>0) {
			try {
				Thread.sleep(2000-(finishTime-startTime));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		runOnUiThread(new Runnable() {
			public void run() {
				if(!isFinished) {
					startActivity(intent);
					overridePendingTransition(R.anim.fade, R.anim.hold);
					finish();
    			}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		MenuItem item = menu.add(Menu.NONE, ID_MENU_Logout, Menu.NONE, R.string.menu_settings_pass);
		item.setShortcut('5', 'x');
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item)
    {
    	//check selected menu item
    	if(item.getItemId() == ID_MENU_Logout)
    	{
    		intent = new Intent(Main.this,StartPage.class);
    		Bundle bundle = new Bundle();
    		bundle.putString("previousID", SharedVariables.mainID);
    		intent.putExtras(bundle);
    		startActivity(intent);
    		this.finish();
    	}
    	return false;
    }

	/**
	 * Called when a multitouch event occurs within a MultitouchGestureListener in this Activity.
	 * 
	 * @param numberOfFingers The number of fingers involved in this gesture
	 * @param gestureType The type of this gesture
	 */
	public void multitouchMotionEvent(int numberOfFingers, GestureType gestureType) {
		if(gestureType == GestureType.DOWN && numberOfFingers == 2){
			startActivity(new Intent(this,BlindUserGatewayPage.class));
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
		}
		else if(gestureType == GestureType.RIGHT && (numberOfFingers == 1 || numberOfFingers == 2)){
			startActivity(new Intent(this,StartPage.class));
			overridePendingTransition(R.anim.fade, R.anim.hold);
			finish();
		}
	}
}
